<?php

declare(strict_types=1);

namespace sheep\library\install\traits;

use sheep\exception\SheepException;
use think\facade\Env as ThinkEnv;
use sheep\traits\Helper;

trait Env
{
    use Helper;

    public $envFilePath = '';


    public function setEnvFilePath() {
        $this->envFilePath = root_path() . '.env';
    }


    /**
     * 重新载入 env 文件
     */
    public function refreshEnvVars()
    {
        ThinkEnv::load($this->envFilePath);
    }


    /**
     * setupJwtKey sets the application encryption key if not set already
     */
    public function setJwtKey()
    {
        if (env('JWT.SECRET')) {
            return;
        }

        $keyVal  = md5(uniqid() . time() . rand(0, 60));

        $this->setEnvVar('JWT.SECRET', $keyVal);

        // 更新配置值
        $this->setConfig('jwt.secret', $keyVal);

        return $keyVal;
    }


    /**
     * setEnvVar writes an environment variable to disk
     */
    public function setEnvVar($key, $value)
    {
        $old = env($key);

        if (strpos($key, '.') !== false) {
            $keyArr = explode('.', $key);
            $key = $keyArr[1] ?? $keyArr[0];
        }

        if (in_array($key, ['APP_DEBUG', 'DEBUG'])) { // 是 true 和 false 的值
            $old = $old ? 'true' : 'false';
        }

        if (file_exists($this->envFilePath)) {
            file_put_contents($this->envFilePath, str_replace(
                "$key = " . $old,
                "$key = " . $value,
                file_get_contents($this->envFilePath)
            ));
        }
    }

}
